package com.zhenyi.youqu.admin.index;

import java.sql.SQLException;
import java.util.List;

import com.baijob.commonTools.DateUtil;
import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.utils.DateUtils;
import com.youqu.common.model.YqApp;
import com.youqu.common.model.YqCategory;
import com.youqu.common.model.YqProduct;
import com.youqu.common.model.YqProductFormat;
import com.youqu.common.model.YqShop;
import com.youqu.common.model.YqShopUser;
import com.zhenyi.core.interceptor.ReferenceInterceptor;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class ProductController extends YQAdminController {

	@Override
	public void list() {
		YqShopUser user = getShopUser();

		Kv kv = getSimpleKv("shopId","categoryId");
		if (!YqShopUser.ROLE_SUPER_ADMIN.equals(user.getRole())) {
			kv.set("appId", user.getAppId());
		}
		if (user.getRole().equals(YqShopUser.ROLE_SHOP)) {
			kv.set("shopId", user.getShopId());
		} else if (user.getRole().equals(YqShopUser.ROLE_INDEPENDENCE_SHOP)) {
			kv.set("shopId", user.getShopId());
		}
		SqlPara sqlPara = db.getSqlPara("YQProducts", kv);
		Page<Record> pages = db.paginate(getPage(), getPageSize(), sqlPara);
		setRainbow(pages);
		// setItems(pages.getList());
		setData("items", pages.getList());
		SqlPara sqlPara2 = db.getSqlPara("YQAdminCategories", Kv.by("appId", user.getAppId()));
		List<YqCategory> categories = YqCategory.dao.find(sqlPara2);
		setData("categories", categories);
		SqlPara sqlPara3 = db.getSqlPara("YQShops", Kv.by("appId", user.getAppId()));
		List<YqCategory> shops = YqCategory.dao.find(sqlPara3);
		setData("shops", shops);
		render("/yq/admin/product/list.html");
	}

	public void add() {
		render("/yq/admin/product/info.html");
	}

	/**
	 * 删除商品
	 */
	@Override
	public void delete() {
		Long productId = getParaToLong("productId");
		if (productId == null) {
			renderMsg("商品id不存在");
			return;
		}
		YqProduct product = YqProduct.dao.findById(productId);
		if (product == null) {
			renderMsg("商品不存在");
			return;
		}
		product.setFlag(1);
		product.update();
		renderSuccess();
	}

	/**
	 * 每个团的情况,列表+团购状态
	 * 
	 * @Time 2019年1月12日 上午11:47:49
	 */
	public void groupList() {
	}

	@Override
	@Before(ReferenceInterceptor.class)
	public void info() {
		YqShopUser shopUser = getShopUser();
		SqlPara sqlPara = db.getSqlPara("YQShops", Kv.by("appId", shopUser.getAppId()));
		List<YqShop> shops = YqShop.dao.find(sqlPara);
		setData("shops", shops);
		Kv kv = Kv.create();
		kv.set("appId", shopUser.getAppId());
		if (shopUser.getRole().equals(YqShopUser.ROLE_INDEPENDENCE_SHOP)) {
			kv.set("shopId", shopUser.getShopId());
		}
		SqlPara sqlPara2 = db.getSqlPara("YQAdminCategories", kv);
		List<YqCategory> categories = YqCategory.dao.find(sqlPara2);
		setData("categories", categories);

		Long productId = getParaToLong("productId");

		if (productId == null) {
			// renderError(404);
			// return;
		}
		YqProduct product = YqProduct.dao.findById(productId);
		if (product == null) {
			product = new YqProduct();
			if (shopUser.getRole().equals(YqShopUser.ROLE_SHOP)) {
				product.setShopId(shopUser.getShopId());
			}
			// renderError(404);
			// return;
		}
		SqlPara spFormat = db.getSqlPara("YQAdminProductFormat", Kv.by("productId", product.getId()));
		List<Record> formats = db.find(spFormat);
		for (Record format : formats) {
			format.set("fee", format.getInt("fee").floatValue() / 100);
		}
		product.set("sizes", formats);
		setInfoItem(product);
		setData(product);
		render("/yq/admin/product/info.html");
	}

	@Override
	public void submit() {
		YqShopUser user = getShopUser();
		YqApp app = YqApp.dao.findByAppId(user.getAppId());
		
		Long productId = getParaToLong("productId");
		Long shopId = getParaToLong("shopId");
		if (shopId == null) {
			renderMsg("请选择商户");
			return;
		}

		String title = getPara("title");
		String subtitle = getPara("subtitle");
		String cover = getPara("cover");
		String intro = getPara("intro");
		String price = getPara("price", "0.0");
		String salePrice = getPara("salePrice", "0.0");
		Integer isGroup = getParaToInt("isGroup", 0);
		Integer isCoupon = getParaToInt("isCoupon", 0);
		Integer isNeedTrack = getParaToInt("isNeedTrack", 0);
		Integer isHidden = getParaToInt("isHidden", 0);
		Integer isHot = getParaToInt("isHot", 0);
		Integer isNew = getParaToInt("isNew", 0);
		Integer groupCount = getParaToInt("groupCount", 0);
		Integer groupHours = getParaToInt("groupHours", 0);
		Integer type = getParaToInt("type", 1); // 1.默认商品,2.餐饮,3.门票,4.报名
		Integer sort = getParaToInt("sort", 1);
		Long storage = getParaToLong("storage", 1L);
		String url = getPara("url");
		String tags = getPara("tags");
		Integer isNeedMoreInfo = getParaToInt("isNeedMoreInfo", 0); // 0.否,1.物流信息,2报名信息（临时）,3.个人信息,4.自定义信息
		String extraJson = getPara("extraJson");
		Long categoryId = getParaToLong("categoryId");
		String shareTitle = getPara("shareTitle", app != null ? app.getName() : "");
		String shareImage = getPara("shareImage", "");
		String sizes = getPara("sizes");
		String images = getPara("images");
		Integer cardType = getParaToInt("cardType", 0); // 0非卡券 1次卡 2日卡 3过期卡
		String cardExpire = getPara("cardExpire");
		Integer cardAvailableDay = getParaToInt("cardAvailableDay");
		Integer cardUseLimit = getParaToInt("cardUseLimit");
		String services = getPara("services");
		String gallery = getPara("gallery");
		String address = getPara("address");
		String latlng = getPara("latlng");

		boolean flag = Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {
				YqProduct product;
				if (productId == null) {
					product = new YqProduct();
					product.setShopId(shopId);
					product.save();
				} else {
					product = YqProduct.dao.findById(productId);
				}
				product.setTitle(title);
				product.setSubtitle(subtitle);
				product.setCover(cover);
				product.setIntro(intro);
				product.setPrice(Float.parseFloat(price));
				product.setSalePrice(Float.parseFloat(salePrice));
				product.setIsGroup(isGroup);
				product.setIsCoupon(isCoupon);
				product.setIsNeedTrack(isNeedTrack);
				product.setIsHidden(isHidden);
				product.setGroupCount(groupCount);
				product.setGroupHours(groupHours);
				product.setSort(sort);
				product.setFee(Integer.parseInt(price.replace(".", "")));
				product.setType(type);
				product.setIsHot(isHot);
				product.setIsNew(isNew);
				product.setStorage(storage);
				product.setUrl(url);
				product.setTags(tags);
				product.setIsNeedMoreInfo(isNeedMoreInfo);
				product.setExtraJson(extraJson);
				product.setCategoryId(categoryId);
				product.setShareTitle(shareTitle);
				product.setShareImage(shareImage);
				// product.setSizes(sizes);
				product.setImages(images);
				product.setCardType(cardType);
				if (cardType > 0) {
					if (StrKit.notBlank(cardExpire)) {
						product.setCardExpire(DateUtil.parse(cardExpire, DateUtils.YYYYMMDD_HHMMSS));
					}
					product.setCardAvailableDay(cardAvailableDay);
					product.setCardUseLimit(cardUseLimit);
				} else {
					product.setCardExpire(null);
					product.setCardAvailableDay(0);
					product.setCardUseLimit(0);
				}
				product.setMinPrice(null);
				product.setMaxPrice(null);
				product.setServices(services);
				product.setGallery(gallery);
				product.setAddress(address);
				product.setLatlng(latlng);
				boolean result = product.update();
				if (!result) {
					return false;
				}

				Kv kv = Kv.by("productId", productId);
				SqlPara sp = db.getSqlPara("YQAdminProductFormat", kv);
				List<YqProductFormat> formats = YqProductFormat.dao.find(sp);
				for (YqProductFormat format : formats) {
					format.setFlag(1);
					if (!format.update()) {
						return false;
					}
				}
				if (JSONUtil.isJson(sizes)) {
					JSONArray jsonArray = JSONUtil.parseArray(sizes);
					Float minPrice = 0f;
					Float maxPrice = 0f;

					for (int i = 0; i < jsonArray.size(); i++) {
						JSONObject obj = jsonArray.getJSONObject(i);
						YqProductFormat format;
						if (obj.getLong("id") != null) {
							format = YqProductFormat.dao.findById(obj.getLong("id"));
						} else {
							format = new YqProductFormat();
						}
						format.setTitle(obj.getStr("title"));
						Float fee = obj.getFloat("fee") * 100;
						format.setFee(fee.intValue());
						format.setImage(obj.getStr("image"));
						format.setStorage(obj.getInt("storage"));
						format.setIsHidden(obj.getInt("isHidden"));
						format.setSort(i);
						format.setProductId(product.getId());
						format.setFlag(0);
						if (!(obj.getLong("id") == null ? format.save() : format.update())) {
							return false;
						}

						if (i == 0) {
							minPrice = obj.getFloat("fee");
							maxPrice = obj.getFloat("fee");
						} else {
							minPrice = obj.getFloat("fee") < minPrice ? obj.getFloat("fee") : minPrice;
							maxPrice = obj.getFloat("fee") > maxPrice ? obj.getFloat("fee") : maxPrice;
						}
					}
					product.setMinPrice(minPrice);
					product.setMaxPrice(maxPrice);
					if (!product.update()) {
						return false;
					}
				}
				return true;
			}
		});
		renderFlag(flag);
	}

	public void updateIsHidden() {
		Long id = getParaToLong("id");
		Integer isHidden = getParaToInt("isHidden", 1);
		if (id == null) {
			renderFailure(500, "product id is null");
			return;
		}
		YqProduct info = YqProduct.dao.findById(id);
		if (info == null) {
			renderError(404);
			return;
		}
		info.setIsHidden(isHidden);
		renderFlag(info.update());
	}
}
